import pandas as pd

print("开始读取文献...")
try:
    unit_file_path = "../final_basic_tables/A075. PCdata基表-3-参考文献表（20250604R1）-1版.xlsx"
    sheet_name = "文献总表"
    df = pd.read_excel(unit_file_path, sheet_name=sheet_name, header=0, skiprows=[1],nrows=2000, engine='openpyxl').fillna('')
except Exception as e:
    print(f"Error reading the Excel file: {e}")
    exit(1)
print("文献读取完毕")

# 检测 sJISSN 超过32字符的行
long_issn_rows = df[df['sJISSN'].str.len() > 128]

if not long_issn_rows.empty:
    print("\n以下行的 sJISSN 值超过128字符限制:")
    print("----------------------------------")
    for index, row in long_issn_rows.iterrows():
        print(f"行号: {index + 2}")  # +2 是因为Python从0开始计数，且跳过了第2行(header=0, skiprows=[1])
        print(f"sJISSN 值: {row['sJISSN']}")
        print(f"长度: {len(row['sJISSN'])}")
        print("----------------------------------")
else:
    print("\n所有 sJISSN 值均未超过128字符限制")

def validate_page_numbers(row):
    max_int = 2147483647  # IntegerField 最大值
    
    # 解析 sPage
    if pd.isna(row['sPage']) or row['sPage'] == "":
        first_page, last_page = None, None
    else:
        if "-" in str(row['sPage']):
            pages = str(row['sPage']).split('-')
            first_page, last_page = pages[0].strip(), pages[1].strip()
        else:
            first_page = last_page = str(row['sPage']).strip()
    
    # 检查是否为合法整数
    def is_valid_integer(value):
        if value is None or value == "":
            return True  # 允许空值
        try:
            num = int(value)
            return 0 <= num <= max_int  # 假设页码不能为负
        except (ValueError, TypeError):
            return False
    
    # 验证 first_page 和 last_page
    first_page_valid = is_valid_integer(first_page)
    last_page_valid = is_valid_integer(last_page)
    
    # 如果不合法，打印警告
    if not first_page_valid or not last_page_valid:
        print(f"⚠️ 行 {row.name + 2} (sPage: '{row['sPage']}') 解析结果无效:")
        print(f"    first_page = {first_page} ({'有效' if first_page_valid else '无效'})")
        print(f"    last_page = {last_page} ({'有效' if last_page_valid else '无效'})")
    
    return first_page_valid and last_page_valid

# 应用检查函数到每一行
df.apply(validate_page_numbers, axis=1)

print("检查完成！")
